<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}
        /resources/admin/easyui/ui/themes/default/easyui.css"/>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}
        /resources/admin/easyui/css/wu.css"/>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}
        /resources/admin/easyui/css/icon.css"/>
    <script type="text/javascript" src="${pageContext.request.contextPath}
        /resources/admin/easyui/js/jquery.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}
        /resources/admin/easyui/ui/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}
        /resources/admin/easyui/ui/locale/easyui-lang-zh_CN.js"></script>
</head>
<body>
<div class="easyui-layout" data-options="fit:true">
    <div data-options="region:'west',border:true,split:true," title="菜单管理" style="width:150px; padding:5px;">
        <ul id="wu-category-tree" class="easyui-tree"></ul>
    </div>
    <div data-options="region:'center',border:false">
        <!-- Begin of toolbar -->
        <div id="wu-toolbar">
            <div class="wu-toolbar-button">
                <a href="#" class="easyui-linkbutton" iconCls="icon-add" onclick="openAdd()" plain="true">添加</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-edit" onclick="openEdit()" plain="true">修改</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-remove" onclick="remove()" plain="true">删除</a>
            </div>
            <div class="wu-toolbar-search">
                <label>关键词：</label><input name="username" class="wu-text" style="width:80px" id="search-value">
                <label>所属角色：</label>
                <select id="search-role" class="easyui-combobox" name="roleId" style="width:80px;">
                    <option value="">全部</option>
                    <c:forEach items="${roleList}" var="role">
                        <option value="${role.id}">${role.name}</option>
                    </c:forEach>
                </select>
                <label>性别：</label>
                <select id="search-sex" class="easyui-combobox" name="sex" style="width:80px;">
                    <option value="-1">全部</option>
                    <option value="0">未知</option>
                    <option value="1">男</option>
                    <option value="2">女</option>
                </select>
                <a id="search-btn" href="#" class="easyui-linkbutton" iconCls="icon-search">开始检索</a>
            </div>
        </div>
        <!-- End of toolbar -->
        <table id="wu-datagrid" class="easyui-treegrid" toolbar="#wu-toolbar"></table>
    </div>
</div>

<style>
    .active {
        background: green;
    }
</style>
<!-- Begin of easyui-dialog -->

<%-- 用户添加部分start --%>
<div id="add-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="width:400px; padding:10px;">
    <form id="add-form" method="post">
        <table>
            <tr>
                <td width="60" align="right">用户名:</td>
                <td><input type="text" name="username" id="add_user_name" value="" class="wu-text"/></td>
            </tr>
            <tr>
                <td align="right">用户密码:</td>
                <td><input type="text" name="password" id="add_password" value="" class="wu-text"/></td>

            </tr>
            <tr>
                <td align="right">所属角色:</td>
                <td>
                    <select class="easyui-combobox" name="roleId" id="add_role_id" style="width:80px;">
                        <option value="" selected="true">请选择</option>
                        <c:forEach items="${roleList}" var="role">
                            <option value="${role.id}">${role.name}</option>
                        </c:forEach>
                    </select>
                </td>
            </tr>
            <tr>
                <td align="right">性别:</td>
                <td>
                    <select class="easyui-combobox" name="sex" id="add_sex" style="width:80px;">
                        <option value="0">未知</option>
                        <option value="1">男</option>
                        <option value="2">女</option>
                    </select></td>

            </tr>
            <tr>
                <td align="right">地址:</td>
                <td><input type="text" name="address" id="add_address" value="" class="wu-text"/></td>

            </tr>
            <tr>
                <td align="right">年龄:</td>
                <td><input type="text" name="age" id="add_age" value="" class="easyui-numberbox" data-options="min:1,precision:0"/></td>

            </tr>
            <tr>
                <td align="right">头像:</td>
                <td><input id="add_photo" name="photo" type="text" placeholder="" value="" class="wu-text" style="width:150px"/>
                    <a href="javascript:void(0)" onClick="addPhoto()" class="easyui-linkbutton" iconCls="icon-upload">添加图片</a></td>
            </tr>
            <tr>
                <td align="right">头像预览:</td>
                <td><img id="preview-photo" src="" alt="" width="100px"></td>
            </tr>

        </table>
    </form>
    <input type="file" id="upload-box" style="display:none;" onchange="upload()">
</div>
<%-- 用户添加部分end --%>


<%-- 用户编辑start --%>
<div id="edit-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="width:400px; padding:10px;">
    <form id="edit-form" method="post">
        <input type="hidden" id="edit_id" name="id"/>
        <table>
            <tr>
                <td width="60" align="right">用户名:</td>
                <td><input type="text" name="username" id="edit_username" value="" class="wu-text"/></td>
            </tr>
            <tr>
                <td align="right">所属角色:</td>
                <td>
                    <select class="easyui-combobox" name="roleId" id="edit_role_id" style="width:80px;">
                        <option value="-1">全部</option>
                        <c:forEach items="${roleList}" var="role">
                            <option value="${role.id}">${role.name}</option>
                        </c:forEach>
                    </select>
                </td>
            </tr>
            <tr>
                <td align="right">性别:</td>
                <td>
                    <select class="easyui-combobox" name="sex" id="edit_sex" style="width:80px;">
                        <option value="-1">全部</option>
                        <option value="0">未知</option>
                        <option value="1">男</option>
                        <option value="2">女</option>
                    </select></td>

            </tr>
            <tr>
                <td align="right">年龄:</td>
                <td><input type="text" name="age" id="edit_age" value=""/></td>

            </tr>
            <tr>
                <td align="right">地址:</td>
                <td><input type="text" name="address" id="edit_address" value="" class="wu-text"/></td>

            </tr>
        </table>
    </form>
</div>
<%-- 用户编辑end --%>

<%-- 编辑角色权限start --%>
<div id="auth-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="width:400px; height:500px; padding:10px;">
    <ul id="auth-tree" class="easyui-tree" checkbox="true">

    </ul>
</div>
<%-- 编辑角色权限end --%>

<div id="icon-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="height:500px;width:580px;
        padding:10px;">

    <form id="icon-form" method="post">
        <table id="icon-table">
        </table>
    </form>
</div>
<!-- End of easyui-dialog -->
<script type="text/javascript">
    function upload() {
        if ($('#upload-box').val() == null) return;
        var formData = new FormData();
        formData.append('photo', document.getElementById('upload-box').files[0])

        $.ajax({
            url: "${pageContext.request.contextPath}/user/upload",
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success: function(data) {
                if (data.type == 'success') {
                    console.log(data)
                    $('#add_photo').val(data.avatar);
                    $('#preview-photo').attr('src', data.avatar);
                    console.log($('#add_photo').val())
                    $.messager.alert("信息提示", data.msg, "info");

                } else {
                    $.messager.alert("信息提示", data.msg , "info");
                }
            },
            error: function() {
                console.log(22)
                $.messager.alert("信息提示", "上传失败", "warning");
            }
        })
    }

    function addPhoto() {
        $('#upload-box').click();
    }

    var existAuthority = null;

    // 判断是否有父类
    function haveParent(rows, parentId) {
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].id == parentId) {
                if (rows[i].parentId != 0) {
                    return true;
                }
            }
        }
        return false;
    }

    // 判断是否被添加
    function isAdded(row, rows) {
        for (var k = 0; k < existAuthority.length; k++) {
            if (existAuthority[k].menuId == row.id && haveParent(rows, row.parentId)) return true;
        }
        return false;
    }


    function convert(rows) {


        // 判断是否有父类
        function exists(rows, parentId) {
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].id == parentId) return true;
            }
            return false;
        }

        var nodes = [];
        // get the top level nodes
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if (!exists(rows, row.parentId)) {
                nodes.push({
                    id: row.id,
                    text: row.menu_name
                });
            }
        }

        var toDo = [];
        for (var i = 0; i < nodes.length; i++) {
            toDo.push(nodes[i]);
        }
        while (toDo.length) {
            var node = toDo.shift();	// the parent node
            // get the children nodes
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                if (row.parentId == node.id) {
                    var child = {id: row.id, text: row.menu_name};
                    if (isAdded(row, rows)) {
                        child.checked = true;
                    }
                    if (node.children) {
                        node.children.push(child);
                    } else {
                        node.children = [child];
                    }
                    toDo.push(child);
                }
            }
        }
        return nodes;
    }

    /*
    * 编辑角色权限
    * */
    function handleAuthEdit(roleId) {


        $('#auth-dialog').dialog({
            closed: false,
            modal: true,
            title: "编辑角色权限",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: authEdit
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#auth-dialog').dialog('close');
                }
            }],
            onBeforeOpen: function () {


                $.ajax({
                    url: '${pageContext.request.contextPath}/role/get_authority_list',
                    type: 'post',
                    data: {roleId: roleId},
                    dataType: 'json',
                    success: function (data) {
                        existAuthority = data;
                    }
                })

                $('#auth-tree').tree({
                    url: "${pageContext.request.contextPath}/role/get_all_menu_list",
                    loadFilter: function (rows) {
                        return convert(rows);
                    }
                })
            }
        });
    }

    function authEdit() {
        var item = $('#wu-datagrid').treegrid('getSelected');
        console.log(item)
        if (item.id == null) {
            $.messager.alert('信息提示', '请选择要删除的角色', 'warning');
            return;
        }

        var ids = '';
        var childrenNodes = $('#auth-tree').tree('getChecked');
        for (var i = 0; i < childrenNodes.length; i++) {
            ids += childrenNodes[i].id + ',';
        }

        var parentNodes = $('#auth-tree').tree('getChecked', 'indeterminate');
        for (var i = 0; i < parentNodes.length; i++) {
            ids += parentNodes[i].id + ',';
        }

        $.ajax({
            url: '${pageContext.request.contextPath}/role/add_authority',
            type: 'post',
            data: {ids: ids, roleId: item.id},
            dataType: 'json',
            success: function (data) {
                if (data.type == 'success') {
                    $.messager.alert('信息提示', data.msg, 'info');
                    $('#auth-dialog').dialog('close');
                } else {
                    $.messager.alert('信息提示', data.msg, 'info');
                }
            }
        })
    }

    /*
    * 搜索
    * */
    $('#search-btn').click(function () {
        var options = {'username': $('#search-value').val()}
        var roleId = $('#search-role').combobox('getValue');
        var sex = $('#search-sex').combobox('getValue');
        if (roleId != -1) {
            options.roleId = roleId;
        }
        if (sex != -1) {
            options.sex = sex;
        }


        $('#wu-datagrid').treegrid('reload', options)
    })


    function select_icon(e) {
        $('.icon-td').removeClass('active');
        $(e).parent('td').addClass('active');
    }

    function addIcon() {
        if ($('#icon-table').children().length <= 0) {
            $.ajax({
                url: '${pageContext.request.contextPath}/menu/select_icon',
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    if (data.type == 'success') {
                        var icon = data.icons;
                        var table = '';

                        for (var i = 0; i < icon.length; i++) {
                            var tbody = '<td class="icon-td"><a id="icon" onclick="select_icon(this)" href="javascript:void(0)" class="' +
                                icon[i] + '" plain="true" >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></td>';
                            if (i == 0) {
                                table += '<tr>' + tbody;
                                continue;
                            }

                            if ((i + 1) % 24 === 0) {
                                table += tbody + '</tr><tr>';
                                continue;
                            }
                            table += tbody;
                        }
                        table += '</tr>';
                        $('#icon-table').append(table);
                    } else {

                    }
                }
            })
        }
        $('#icon-form').form('clear');
        $('#icon-dialog').dialog({
            closed: false,
            modal: true,
            title: "添加菜单信息",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    /*
                    * 获取图标信息
                    * */
                    var iconName = $('.active a').attr('class');
                    $('#add-icon').val(iconName);
                    $('#edit_icon').val(iconName);
                    $('#icon-dialog').dialog('close');
                    $('#wu-datagrid').datagrid('reload');
                }
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#icon-dialog').dialog('close');
                }
            }]
        });
    }

    /**
     * Name 添加记录
     */
    function add() {
        // var validate = $('#-form').form("validate");
        // if(!validate) {
        // $.message.alert("消息提示", "请检查你输入的数据!", "warning");
        // return;
        // }

        var data = $('#add-form').serialize();
        console.log(data);

        $.ajax({
            url: '${pageContext.request.contextPath}/user/add_user',
            data: data,
            type: 'post',
            dataType: 'json',
            success: function (data) {
                if (data.type == 'success') {
                    $.messager.alert('信息提示', data.msg, 'info');
                    $('#add-dialog').dialog('close');
                    $('#icon-dialog').dialog('close');
                    $('#wu-datagrid').treegrid('reload');
                } else {
                    $.messager.alert('信息提示', data.msg, 'info');
                }
            }
        });
    }

    /**
     * Name 修改记录
     */
    function edit() {

        var data = $('#edit-form').serialize();
        console.log(data)

        $.ajax({
            url: '${pageContext.request.contextPath}/user/edit_user',
            data: data,
            type: 'post',
            dataType: 'json',
            success: function (data) {
                if (data.type == 'success') {
                    $.messager.alert('信息提示', data.msg , 'info');
                    $('#edit-dialog').dialog('close');
                    $('#icon-dialog').dialog('close');
                    $('#wu-datagrid').treegrid('reload');
                } else {
                    $.messager.alert('信息提示', data.msg, 'info');
                }
            }
        });
    }

    /**
     * Name 删除记录
     */
    function remove() {
        $.messager.confirm('信息提示', '确定要删除该记录？', function (result) {
            if (result) {
                var item = $('#wu-datagrid').datagrid('getSelections');
                if (item == null ) {
                    $.messager.alert('信息提示', '请选择要删除的角色', 'warning');
                    return;
                }
                var ids = '';
                for(var i=0; i<item.length; i++) {
                    ids += item[i].id + ',';
                }
                console.log(ids)
                $.ajax({
                    url: '${pageContext.request.contextPath}/user/delete_user',
                    type: 'post',
                    data: {ids: ids},
                    dataType: 'json',
                    success: function (data) {
                        if (data.type == 'success') {
                            $.messager.alert('信息提示', data.msg, 'info');
                            $('#wu-datagrid').treegrid('reload');
                        } else {
                            $.messager.alert('信息提示', data.msg, 'info');
                        }
                    }
                });
            }
        });
    }

    /**
     * Name 打开添加窗口
     */
    function openAdd() {
        $('#add-form').form('clear');
        $('#add-dialog').dialog({
            closed: false,
            modal: true,
            title: "添加菜单信息",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: add
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#add-dialog').dialog('close');
                }
            }]
        });
    }

    /**
     * Name 打开修改窗口
     */
    function openEdit() {
        $('#edit-form').form('clear');
        var items = $('#wu-datagrid').treegrid('getSelections');

        if (items == null || items.length == 0) {
            $.messager.alert('信息提示', '请选择至少一条记录！', 'warning');
            return
        }

        if (items.length > 1) {
            $.messager.alert('信息提示', '请选择最多一条记录进行修改！', 'warning');
            return
        }

        var item = items[0];
        console.log(item)

        $('#edit-dialog').dialog({
            closed: false,
            modal: true,
            title: "修改信息",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: edit
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#edit-dialog').dialog('close');
                }
            }],
            onBeforeOpen: function () {
                $('#edit_id').val(item.id);
                $('#edit_username').val(item.username);
                $('#edit_address').val(item.address);
                $('#edit_age').val(item.age);
                $('#edit_sex').combobox('setValue', item.sex);
                $('#edit_role_id').combobox('setValue', item.roleId);

            }
        });
    }

    /**
     * Name 载入数据
     */
    $('#wu-datagrid').treegrid({
        url: '${pageContext.request.contextPath}/user/get_list',
        rownumbers: true,
        singleSelect: false,
        pageSize: 20,
        pagination: true,
        multiSort: true,
        fitColumns: true,
        fit: true,
        idField: 'id',
        treeField: 'username',
        columns: [[
            {field: 'chk', checkbox: true},
            {field: 'username', title: '用户名', width: 100},
            {field: 'password', title: '密码', width: 100},
            {field: 'age', title: '年龄', width: 100},
            {field: 'sex', title: '性别', width: 100, formatter: function(value, row, index) {
                    if (value == 0) {
                        return '未知';
                    } else if (value == 1) {
                        return '男';
                    } else {
                        return '女';
                    }
                }},
            {field: 'address', title: '地址', width: 100},
            {field: 'photo', title: '头像', width: 100},
            {field: 'roleId', title: '所属角色', width: 100, formatter: function (value, row, index) {
                    var data = $('#search-role').combobox('getData');
                    for(var i=0; i<data.length; i++) {
                        if (data[i].value == value) {
                            return data[i].text;
                        }
                    }
                    return value;
                }}
        ]]
    });
</script>
</body>
</html>